﻿/****************************** Module Header ******************************\
 * Module Name:  WSDLHelper.cs
 * Module Version:  1.0.0 (2013-6-19)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is used to process the webservices.
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Web.Services.Description;
using System.Data;

namespace UCF.Core
{
    // 2013-6-19 by sutroon
    public class WSDLHelper
    {
        /// <summary>
        /// WebServices地址
        /// </summary>
        public static string Uri { get; set; }

        private static Type Instance;

        public static Action<string> ShowMessageHandler { get; set; }

        public static Exception ExceptionObject { get; set; }

        public static bool IsDebug { get; set; }

        public static bool Enable { get; set; }

        /// <summary>
        /// 对返回值判断：if(obj is Exception) MessageBox.Show(((Exception)obj).Message);
        /// </summary>
        /// <param name="namespace"></param>
        /// <returns></returns>
        public static object GetInstance(string @namespace = "sowsdl")
        {
            try
            {
                //获取WSDL
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(Uri + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                string classname = sd.Services[0].Name;
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                //ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例，并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Instance = assembly.GetType(@namespace + "." + classname, true, true);
                ExceptionObject = null;
                Enable = true;
                return Instance;
            }
            catch (Exception ex)
            {
                Enable = false;
                ExceptionObject = ex;
                return null;
            }
        }

        public static object InvokeMethod(string methodname, object[] args)
        {
            if (Instance == null)
            {
                ExceptionObject = new Exception("远程服务器未连接");
                return null;
            }
            try
            {
                object obj = Activator.CreateInstance(Instance);
                System.Reflection.MethodInfo mi = Instance.GetMethod(methodname);
                ExceptionObject = null;
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                ExceptionObject = ex;
                return ex;
            }
        }
        public static T InvokeMethod<T>(string methodname, object[] args)
        {
            if (Instance == null)
            {
                ExceptionObject = new Exception("远程服务器未连接");
                return default(T);
            }
            try
            {
                object obj = Activator.CreateInstance(Instance);
                System.Reflection.MethodInfo mi = Instance.GetMethod(methodname);
                ExceptionObject = null;
                object result = mi.Invoke(obj, args);
                if (result.GetType() == typeof(T))
                {
                    return (T)result;
                }
                else
                {
                    return default(T);
                }
            }
            catch (Exception ex)
            {
                ExceptionObject = ex;
            }
            return default(T);
        }

        public static object InvokeWebService(string url, string methodname, object[] args, out string msg, string @namespace = "sowsdl")
        {
            try
            {
                //获取WSDL
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                string classname = sd.Services[0].Name;
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                //ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例，并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                msg = "SUCCESS";
                Enable = true;
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                msg = ex.InnerException.Message;
                Enable = false;
                return ex;
            }
        }

        public static string DBExecute(string coid, string sql)
        {
            return InvokeMethod<string>("ExecuteSql", new object[] { coid, sql });
        }

        public static DataTable DBSelect(string coid, string sql)
        {
            return InvokeMethod<DataTable>("ExecuteDataTable", new object[] { coid, sql });
        }

        public static DataTable DBSelect(string coid, string tblName, string search, string fields, string method = "SelectTable")
        {
            return InvokeMethod<DataTable>(method, new object[] { coid, tblName, search, fields });
        }

        public static string DBSelectTreeXml(string coid, string sqlfmt, string pid, string sqlfmtItems, string sqlfmtParent)
        {
            return InvokeMethod<string>("SelectTreeXml", new object[] { coid, sqlfmt, pid, sqlfmtItems, sqlfmtParent });
        }

        public static DataTable DBSelectTreeTable(string coid, string sqltpl, string pid)
        {
            return InvokeMethod<DataTable>("SelectTreeTable", new object[] { coid, sqltpl, pid });
        }

        public static DataTable DBSelectPaging(string coid, string fromsql, string orderby, string fields, out int recordcount, out int pagecount, int pageid, int pagesize)
        {
            int c = 0, d = 0;
            object[] args = new object[] { coid, fromsql, orderby, fields, pageid, pagesize, c, d };
            DataTable dt = WSDLHelper.InvokeMethod<DataTable>("ExecutePagingDataTable", args);
            recordcount = c;
            pagecount = d;
            return dt;
        }

        public static string DBDelete(string coid, string tblName, string search)
        {
            return InvokeMethod<string>("DeleteRecords", new object[] { coid, tblName, search });
        }
        public static string DBInsert(string coid, string tblName, string fields, string values)
        {
            return InvokeMethod<string>("InsertRecord", new object[] { coid, tblName, fields, values });
        }

        public static string DBUpdate(string coid, string tblName, string fieldandvalues, string search)
        {
            return InvokeMethod<string>("UpdateRecords", new object[] { coid, tblName, fieldandvalues, search });
        }

        public static bool Test()
        {
            return InvokeMethod<bool>("Test", null);
        }

        public static void ShowMessage(string funcName)
        {
            if (ShowMessageHandler != null) ShowMessageHandler(GetExceptionMessage("{0}数据读取失败,原因是:".Fmt(funcName)));
        }

        public static void Dispose()
        {
            ExceptionObject = null;
            Instance = null;
        }

        public static string GetExceptionMessage(string title = "数据读取失败,原因是", string ln = "")
        {
            if (ExceptionObject == null) return "WSDL - UnFound Exception!";
            if (ln.Length == 0) ln = Environment.NewLine;
            StringBuilder sb = new StringBuilder();
            if (title.Length > 0) sb.AppendFormat("{0}：{1}", title, ln);
            sb.AppendFormat("{0}{1}", ExceptionObject.Message, ln);
            if (ExceptionObject.InnerException != null)
            {
                if (IsDebug)
                {
                    sb.Append(ExceptionObject.InnerException.Message);
                }
                else
                {
                    int i = ExceptionObject.InnerException.Message.IndexOf("\n");
                    if (i > -1) sb.Append(ExceptionObject.InnerException.Message.Substring(0, i));
                }
            }
            return sb.ToString();
        }
    }
}
